import React, { useMemo } from 'react';
import { 
  List, 
  Card, 
  Tag, 
  Button, 
  Select, 
  Space, 
  Typography, 
  Empty, 
  Spin,
  Tooltip,
  Badge
} from 'antd';
import { 
  EyeOutlined, 
  EditOutlined, 
  FileTextOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined
} from '@ant-design/icons';
import { SearchResult, SearchConfig } from '../../../services/search/types';
import { Content, ContentType } from '../../../types/document';
import dayjs from 'dayjs';

const { Text, Paragraph, Title } = Typography;
const { Option } = Select;

interface SearchResultsProps {
  results: SearchResult[];
  loading: boolean;
  config: SearchConfig;
  onResultClick: (document: Content) => void;
  onConfigChange: (config: Partial<SearchConfig>) => void;
  total?: number;
  className?: string;
}

export const SearchResults: React.FC<SearchResultsProps> = ({
  results,
  loading,
  config,
  onResultClick,
  onConfigChange,
  total,
  className
}) => {
  // 排序选项
  const sortOptions = [
    { label: '相关性', value: 'relevance', icon: <SortDescendingOutlined /> },
    { label: '时间', value: 'date', icon: <SortDescendingOutlined /> },
    { label: '标题', value: 'title', icon: <SortAscendingOutlined /> },
    { label: '大小', value: 'size', icon: <SortDescendingOutlined /> }
  ];

  // 获取内容类型图标
  const getContentTypeIcon = (type: ContentType) => {
    switch (type) {
      case ContentType.TEXT_DOCUMENT:
        return <FileTextOutlined />;
      case ContentType.STORYBOARD:
        return <FileTextOutlined />; // 后续可以换成分镜专用图标
      case ContentType.DATA_COLLECTION:
        return <FileTextOutlined />; // 后续可以换成数据专用图标
      default:
        return <FileTextOutlined />;
    }
  };

  // 获取内容类型标签颜色
  const getContentTypeColor = (type: ContentType) => {
    switch (type) {
      case ContentType.TEXT_DOCUMENT:
        return 'blue';
      case ContentType.STORYBOARD:
        return 'green';
      case ContentType.DATA_COLLECTION:
        return 'orange';
      default:
        return 'default';
    }
  };

  // 获取内容类型名称
  const getContentTypeName = (type: ContentType) => {
    switch (type) {
      case ContentType.TEXT_DOCUMENT:
        return '文本文档';
      case ContentType.STORYBOARD:
        return '分镜脚本';
      case ContentType.DATA_COLLECTION:
        return '数据采集';
      default:
        return '未知类型';
    }
  };

  // 计算文档大小
  const getDocumentSize = (document: Content) => {
    let size = document.title.length;
    if (document.type === ContentType.TEXT_DOCUMENT) {
      size += (document.data.content || '').length;
    }
    return size;
  };

  // 格式化文档大小
  const formatSize = (size: number) => {
    if (size < 1000) return `${size} 字符`;
    if (size < 1000000) return `${(size / 1000).toFixed(1)}K 字符`;
    return `${(size / 1000000).toFixed(1)}M 字符`;
  };

  // 高亮搜索关键词
  const highlightText = (text: string, highlights: any[]) => {
    if (!highlights.length || !config.query) return text;
    
    let highlightedText = text;
    const query = config.query.toLowerCase();
    
    // 简单的高亮实现
    const regex = new RegExp(`(${query})`, 'gi');
    highlightedText = text.replace(regex, '<mark>$1</mark>');
    
    return <span dangerouslySetInnerHTML={{ __html: highlightedText }} />;
  };

  // 渲染结果项
  const renderResultItem = (result: SearchResult) => {
    const { document, score, highlights, matchedFields } = result;
    const size = getDocumentSize(document);

    return (
      <List.Item
        key={document.id}
        className="search-result-item"
        actions={[
          <Tooltip title="查看">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => onResultClick(document)}
            />
          </Tooltip>,
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => onResultClick(document)}
            />
          </Tooltip>
        ]}
      >
        <List.Item.Meta
          avatar={
            <div className="result-avatar">
              {getContentTypeIcon(document.type)}
            </div>
          }
          title={
            <div className="result-title">
              <Space>
                {highlightText(document.title, highlights.filter(h => h.field === 'title'))}
                {config.sortBy === 'relevance' && (
                  <Badge 
                    count={Math.round(score * 100)} 
                    style={{ backgroundColor: '#1890ff' }}
                    title={`相关性: ${Math.round(score * 100)}%`}
                  />
                )}
              </Space>
            </div>
          }
          description={
            <div className="result-description">
              {/* 内容预览 */}
              {highlights.some(h => h.field === 'content') ? (
                <Paragraph 
                  ellipsis={{ rows: 2, expandable: false }}
                  className="result-content"
                >
                  {highlights
                    .filter(h => h.field === 'content')
                    .slice(0, 1)
                    .map((highlight, index) => (
                      <span key={index}>
                        {highlightText(highlight.text, [highlight])}
                      </span>
                    ))
                  }
                </Paragraph>
              ) : (
                <Paragraph 
                  ellipsis={{ rows: 2, expandable: false }}
                  className="result-content"
                >
                  {document.type === ContentType.TEXT_DOCUMENT 
                    ? (document.data.content || '无内容').substring(0, 200)
                    : '暂无预览'
                  }
                </Paragraph>
              )}

              {/* 元数据 */}
              <div className="result-meta">
                <Space size="small">
                  <Tag 
                    color={getContentTypeColor(document.type)}
                    icon={getContentTypeIcon(document.type)}
                  >
                    {getContentTypeName(document.type)}
                  </Tag>
                  
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {formatSize(size)}
                  </Text>
                  
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {dayjs(document.updatedAt).format('YYYY-MM-DD HH:mm')}
                  </Text>

                  {matchedFields.length > 0 && (
                    <Tooltip title={`匹配字段: ${matchedFields.join(', ')}`}>
                      <Tag size="small" color="processing">
                        {matchedFields.length} 个匹配
                      </Tag>
                    </Tooltip>
                  )}
                </Space>
              </div>
            </div>
          }
        />
      </List.Item>
    );
  };

  // 渲染空状态
  const renderEmpty = () => {
    if (config.query.trim()) {
      return (
        <Empty
          description={
            <div>
              <p>未找到包含 "{config.query}" 的文档</p>
              <p style={{ color: '#999', fontSize: '14px' }}>
                尝试使用不同的关键词或调整筛选条件
              </p>
            </div>
          }
        />
      );
    }
    
    return (
      <Empty
        description="请输入搜索关键词查找文档"
      />
    );
  };

  return (
    <div className={`search-results ${className || ''}`}>
      {/* 结果工具栏 */}
      {(results.length > 0 || loading) && (
        <Card size="small" className="results-toolbar">
          <div className="toolbar-content">
            <div className="results-info">
              {loading ? (
                <Text>搜索中...</Text>
              ) : (
                <Text>
                  找到 <Text strong>{results.length}</Text> 个结果
                  {total !== undefined && total !== results.length && (
                    <Text type="secondary"> (共 {total} 个)</Text>
                  )}
                  {config.query && (
                    <Text type="secondary"> 关于 "{config.query}"</Text>
                  )}
                </Text>
              )}
            </div>

            <div className="sorting-controls">
              <Space>
                <Text type="secondary">排序:</Text>
                <Select
                  value={config.sortBy}
                  size="small"
                  style={{ width: 120 }}
                  onChange={(sortBy) => onConfigChange({ sortBy })}
                >
                  {sortOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      <Space>
                        {option.icon}
                        {option.label}
                      </Space>
                    </Option>
                  ))}
                </Select>

                <Button
                  size="small"
                  type="text"
                  icon={config.sortOrder === 'desc' ? <SortDescendingOutlined /> : <SortAscendingOutlined />}
                  onClick={() => onConfigChange({ 
                    sortOrder: config.sortOrder === 'desc' ? 'asc' : 'desc' 
                  })}
                  title={config.sortOrder === 'desc' ? '降序' : '升序'}
                />
              </Space>
            </div>
          </div>
        </Card>
      )}

      {/* 搜索结果列表 */}
      <Spin spinning={loading}>
        {results.length > 0 ? (
          <List
            className="results-list"
            dataSource={results}
            renderItem={renderResultItem}
            pagination={results.length > 20 ? {
              pageSize: 20,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) => 
                `${range[0]}-${range[1]} / 共 ${total} 个结果`
            } : false}
          />
        ) : (
          renderEmpty()
        )}
      </Spin>

      <style jsx>{`
        .search-results {
          background: #fff;
          border-radius: 8px;
        }

        .search-results :global(.results-toolbar) {
          margin-bottom: 16px;
          border-radius: 6px;
        }

        .search-results :global(.toolbar-content) {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .search-results :global(.results-list) {
          background: #fff;
        }

        .search-results :global(.search-result-item) {
          padding: 16px;
          border-bottom: 1px solid #f0f0f0;
          cursor: pointer;
          transition: background-color 0.2s;
        }

        .search-results :global(.search-result-item:hover) {
          background-color: #fafafa;
        }

        .search-results :global(.result-avatar) {
          width: 40px;
          height: 40px;
          border-radius: 6px;
          background: #f5f5f5;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          color: #1890ff;
        }

        .search-results :global(.result-title) {
          margin-bottom: 8px;
        }

        .search-results :global(.result-content) {
          margin: 8px 0;
          color: #666;
        }

        .search-results :global(.result-meta) {
          margin-top: 8px;
        }

        .search-results :global(mark) {
          background-color: #fff2b8;
          padding: 0 2px;
          border-radius: 2px;
        }

        @media (max-width: 768px) {
          .search-results :global(.toolbar-content) {
            flex-direction: column;
            gap: 12px;
          }
          
          .search-results :global(.sorting-controls) {
            width: 100%;
            justify-content: center;
          }
        }
      `}</style>
    </div>
  );
};

export default SearchResults;